﻿#include "CmdHandler.h"
#include "DataPack.h"
#include "Cmd.h"
#include <iostream>
#include "cocos2d.h"
#include "Socket.h"
#include "CCLuaEngine.h"
using namespace  cocos2d;
using namespace std;
SingletonCPP(CmdHandler)

void CmdHandler::PushCmd(Cmd*cmd)
{
	CCDirector::getInstance()->getScheduler()->performFunctionInCocosThread([=]()
	{
		LuaStack* stack = LuaEngine::getInstance()->getLuaStack();
		if (!stack)return;
		lua_State* ss = stack->getLuaState();
		if (!ss)return;
		auto top = lua_gettop(ss);
		lua_getglobal(ss, "PARSE_PROTO_MSG");
		lua_pushstring(ss, cmd->buffer);
		lua_call(ss, 1, 0);
		lua_settop(ss, top);
	});
}             

void CmdHandler::PushDataPack(DataPack*pack)
{
	CCDirector::getInstance()->getScheduler()->performFunctionInCocosThread([=]()
	{
		LuaStack* stack = LuaEngine::getInstance()->getLuaStack();
		if (!stack)return;
		lua_State* ss = stack->getLuaState();
		if (!ss)return;
		auto top = lua_gettop(ss);
		lua_getglobal(ss, "PARSE_PROTO_CMD_MSG");
		lua_pushstring(ss, pack->buffer);
		lua_call(ss, 1, 0);
		lua_settop(ss, top);
		stack->clean();
		//	cmd->release();
	});
}

void CmdHandler::SendCmd(Cmd*cmd)
{
	DataPack*pack = DataPack::CreateWithCmd(cmd, false);
	Socket::GetInstance()->PushDataPack(pack);
}

void CmdHandler::PushProtoData(const std::string &data)
{
	Socket::GetInstance()->PushProtoData(data);
}

void CmdHandler::PushRawData(const char *data, int size)
{
	Socket::GetInstance()->PushRawData(data,size);
}